package com.jiinfo.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.plugin.activerecord.Record;
import com.jiinfo.model.Resource;
import com.jiinfo.util.StringUtils;

public class AuthInterceptor implements Interceptor{

	private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
	
	private static Map<String,Record> urls=new HashMap<String, Record>();
	private static Map<String,Record> codes=new HashMap<String, Record>();
	
	
	
	public void intercept(Invocation inv) {
		
		if(urls.size()==0||codes.size()==0){

			logger.info("初始化全局权限信息！");
			
			List<Record> list=Resource.dao.getAllResources();
			for (Record record : list) {
				String url=record.getStr("url");
				String code=record.getStr("code");
				if(!StringUtils.isEmpty(url)){
					url=formatUrl(url);
					urls.put(url, record);
				}
				if(!StringUtils.isEmpty(code)){
					codes.put(code, record);
				}
			}
		}
		String actionKey=inv.getActionKey();
		actionKey=formatUrl(actionKey);
		//TODO 
		//此处有BUG，如果 定义成 /manage/user/edit  /manage/user 就会出现授权成功的问题
		if(urls.containsKey(actionKey)){
			Subject subject = SecurityUtils.getSubject();
			if(subject.isAuthenticated()||subject.isRemembered()){
				//如果用户已认证
				Record record=urls.get(actionKey);
				String code=record.getStr("code");
				
				if(subject.isPermitted(code)){
					inv.invoke();
				}else{
					//转到没有权限的页面
					inv.getController().renderJsp("/noAuth.jsp");
				}
			}else{
				//转到登录页面
				//可能有后台和前台的登录，可根据当前的url跳转到相应的页面，也可能后台和前台分开两个系统。
				inv.getController().redirect("/manage");
			}
		}else{
			inv.invoke();
		}
		
		
	}
	
	
	private String formatUrl(String url){
		if(!url.startsWith("/")){
			url="/"+url;
		}
		if(!url.endsWith("/")){
			url=url+"/";
		}
		return url;
	}

}
